package com.njpi.stu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomUserDetailsService customUserDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("pxl").password(passwordEncoder().encode("123456"))
                .roles("student");*/
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/user/register/**").permitAll()
                .antMatchers("/user/sendSms/**").permitAll()
                .antMatchers("/logout").permitAll();

        http.authorizeRequests().antMatchers("/").permitAll()
                //根据角色分配路径权限尚未完成
                /*.antMatchers("/**").hasRole("TEACHER")
                .antMatchers("/**").hasRole("STUDENT")
                .antMatchers("/**").hasRole("DBA")*/
                .anyRequest().authenticated();
        http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login")/*.successForwardUrl("/home")*/;

        //开启自动配置的注销功能。
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login");

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remeber");
    }


    @Override
    public void configure(WebSecurity web) {
        web.ignoring().mvcMatchers("/css/**")
                .mvcMatchers("/js/**")
               // .mvcMatchers("/**/*.html")
                .mvcMatchers("/fonts/**")
                .mvcMatchers("/favicon.ico")
                .mvcMatchers("/images/**");
    }
}
